import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ActivatedRoute } from '@angular/router';
import { sncodeStatusArrs } from '../../xstorage-manage-pipes/storage-manage-z.pipe';
import { CommonService } from '../../../../services-common/common.service';
import { StorageCommonService } from '../../xstorage-manage-services/storage-common.service';
import { StorageManageStockService } from '../../xstorage-manage-services/storage-manage-stock.service';

@Component({
  selector: 'app-storage-stock-sncode',
  templateUrl: './storage-stock-sncode.component.html',
  styleUrls: ['./storage-stock-sncode.component.scss']
})
export class StorageStockSncodeComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;

  routeParams: any = {};
  searchOptions = [
    { type: 1, labelText: 'SN码', valueKey: 'snCode', value: '' },
    { type: 1, labelText: '商品', valueKey: 'goods', value: '', placeholder: '69码/商品编码/名称' },
    {
      type: 2,
      labelText: 'SN状态',
      valueKey: 'state',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [...sncodeStatusArrs]
    },
    // {
    //   type: 2,
    //   labelText: 'SN类型',
    //   valueKey: 'type',
    //   value: [],
    //   multiple: false,
    //   notTostr: false,
    //   selectBindKey: { key: 'value', label: 'label' },
    //   selectOptions: [
    //     {value: 0, label: '入库单'},
    //     {value: 1, label: '出库单'}
    //   ]
    // },
    {
      type: 2,
      labelText: '仓库',
      valueKey: 'whId',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '库位',
      valueKey: 'libraryId',
      value: [],
      multiple: true,
      notTostr: false,
      selectBindKey: { key: 'id', label: 'name' },
      selectOptions: []
    },
    {
      type: 2,
      labelText: '品质',
      valueKey: 'quality',
      value: [],
      multiple: false,
      notTostr: false,
      selectBindKey: { key: 'value', label: 'label' },
      selectOptions: [
        {value: 0, label: '不良品'},
        {value: 1, label: '良品'}
      ]
    },
    { type: 1, labelText: '关联单号', valueKey: 'relationNo', value: '', placeholder: '入库/出库关联单号' },
    { type: 3, labelText: '入库时间', valueKey: ['warehousingTime', 'warehousingEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '出库时间', valueKey: ['deliveryTime', 'deliveryEndTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tbWidthConfig: Array<string> = ['180px', '120px', '120px', '120px', '120px', '180px', '170px', '180px', '170px', '200px', '120px', '250px', '180px', '160px', '160px'];
  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  // 跟进 Modal
  initParams: any = {
    type: 2, // type  1、采购 2、SN码信息
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收(modelId暂无用)
    relationInformation: ''
  };

  // export
  exportLoading = false;

  warehouseOptions: any[] = []; // 仓库Option
  locationOptions: any[] = []; // 库位Option

  constructor(
    private msg: NzMessageService,
    private modal: NzModalService,
    private activatedRoute: ActivatedRoute,
    private commonService: CommonService,
    private storageCommonService: StorageCommonService,
    private services: StorageManageStockService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
      this.searchOptions[1].value = res.goodsCode || '';
    })
  }

  ngOnInit(): void {
    this.loadWarehouseOptions();
    this.loadLocationOptions();
  }

  // 查询仓库Options
  async loadWarehouseOptions() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getWarehouseList(params);
    if (code === 0) {
      this.warehouseOptions = data.records || [];
      this.setSearchOption(data.records, 'whId');
    } else {
      this.msg.error(message);
    }
  }

  // 查询库位Options
  async loadLocationOptions() {
    let params = {
      // whId: '',
      page: 1,
      pageSize: 1000
    }
    const {code, data, message}: any = await this.storageCommonService.getLocationList(params);
    if (code === 0) {
      this.locationOptions = data.records || [];
      this.setSearchOption(data.records, 'libraryId');
    } else {
      this.msg.error(message);
    }
  }
  
  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const {code , data, message}: any = await this.services.getSncodeList(params);
    this.tableParams.loading = false;
    
    if (code === 0) {
      const {records, total} = data.list || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.msg.error(message);
    }
  }

  queryResetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // export
  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        this.exportLoading = true;
        const res: any = await this.services.exportSncodeData({...this.searchParams});
        this.exportLoading = false;

        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, 'SN码信息');
        } else {
          this.msg.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 跟进
  showFollowModal(item: any) {
    this.initParams.relationInformation = item.id;
    this.followUpRef.isModelVisible = true;
  }

  setSearchOption(array: Array<any>, val: string) {
    let temIndex = this.searchOptions.findIndex(item => item.valueKey === val);
    this.searchOptions[temIndex].selectOptions = array || [];
  }

  // Filter Text
  filterText(array: Array<any>, keyVal: any) {
    let tempObjs: any = {};
    if (array.length) {
      tempObjs = array.find(item => item.id === keyVal);
    }

    return tempObjs?.name || '-';
  }
}
